package com.lnsf.bookstore.system.book.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lnsf.bookstore.system.book.dao.BookMapper;
import com.lnsf.bookstore.system.book.service.BookService;
import com.lnsf.bookstore.system.book.vo.Book;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private SolrServer solrServer;

    /**
     * 商品信息导入索引库
     * 需要展示给用户的字段、需要搜索的字段需要添加到索引库。
     * 比如商品的id、商品的名称、商品的卖点、商品的价格、商品的图片、商品的分类名称。
     * @return
     */
    @Override
    public Object importItemToIndex() throws IOException, SolrServerException {
        List<Book> bookList = bookMapper.selectAll();
        //将图书商品列表导入Solr
        for(Book book: bookList){
            SolrInputDocument document = new SolrInputDocument();
            document.addField("id",book.getId());
            document.addField("book_pic",book.getPic());
            document.addField("book_price",book.getUnitPrice());
            document.addField("book_category_name",book.getCategory().getName());
            //将文档写入索引库
            solrServer.add(document);
        }

        //提交
        solrServer.commit();
        return null;
    }

    @Override
    public PageInfo<Book> selectAll(Map<String, Object> map, Book book) {
        if(map.get("page")!=null && map.get("limit")!=null) {
            PageHelper.startPage(Integer.parseInt(map.get("page").toString()), Integer.parseInt(map.get("limit").toString()));
        }
        return new PageInfo<Book>(bookMapper.selectAll());
    }

    @Override
    public Book queryObject(Integer id) {
        return bookMapper.selectByPrimaryKey(id);
    }

    @Override
    public int deleteBatch(Integer[] ids) {
        return bookMapper.deleteBatch(ids);
    }

    @Override
    public int update(Book book) {
        return bookMapper.updateByPrimaryKeySelective(book);
    }

    @Override
    public int save(Book book) {
        return bookMapper.insert(book);
    }
}
